package middleware

import (
	"github.com/kataras/iris/v12"
	"micro-grpc-server/app/common"
	"micro-grpc-server/app/conf"
	"micro-grpc-server/library/encrypt"
	"sync"
)

var AuthLogin *authLoginMiddleware

func init() {
	var once sync.Once
	once.Do(func() {
		AuthLogin = &authLoginMiddleware{}
	})
}

type authLoginMiddleware struct{}

func (m *authLoginMiddleware) LoginByToken(ctx iris.Context) {
	authorization := ctx.GetHeader("Authorization")
	if len(authorization) > 7 {
		accessToken := authorization[7:]
		if len(accessToken) > 0 {
			m.LoginByAccessToken(accessToken, ctx)
		}
	} else if auth := common.SessManager.Start(ctx).Get("auth_admin_user_id"); auth != nil {
		ctx.Values().Set("auth_user_id", auth)
	}

	ctx.Next()
}

func (m *authLoginMiddleware) LoginByAccessToken(accessToken string, ctx iris.Context) {
	u := encrypt.CheckSignature(accessToken, conf.Instance.Encrypt.TokenSalt)
	if u != nil {
		ctx.Values().Set("auth_user_id", u.UserId)
		ctx.Values().Set("auth_user_name", u.Name)
		ctx.Values().Set("auth_user_avatar", u.Avatar)
	}
}
